import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

/// 解决滚动到边缘不能触发外部 PageView 滑动的问题

class ContinueScroll extends StatefulWidget {
  final PageController pageController;
  final Widget child;

  ContinueScroll({
    required this.pageController,
    required this.child,
  });

  @override
  _ContinueScrollState createState() => _ContinueScrollState();
}

class _ContinueScrollState extends State<ContinueScroll> {
  DragStartDetails? _dragStartDetails;
  Drag? _drag;

  @override
  Widget build(BuildContext context) {
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollStartNotification &&
            notification.dragDetails != null) {
          //滑动起始的通知先存起来
          _dragStartDetails = notification.dragDetails!;
        }

        if (notification is OverscrollNotification &&
            notification.dragDetails != null &&
            _dragStartDetails != null) {
          //当发生OverScroll的时候，生成外部滑动的drag对象
          _drag =
              widget.pageController.position.drag(_dragStartDetails!, () {});
          //使用外部滑动的drag对象进行滑动
          _drag!.update(notification.dragDetails!);
        }

        if (notification is ScrollEndNotification && _drag != null) {
          //滑动结束后取消
          _drag!.cancel();
        }
        return true;
      },
      child: widget.child,
    );
  }
}
